package com.cim.controllers
{
	import com.cim.model.ClasificadorNaranjas;
	import com.cim.model.MainModel;
	import com.cim.utils.NaranjaFactory;
	import com.cim.view.MainView;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import mx.charts.LinearAxis;
	import mx.controls.Alert;
	import mx.graphics.SolidColor;

	public class MainController
	{
		private const INITIAL:String = 'inicial';
		private const PAUSED:String = 'pausado';
		private const RUNNING:String = 'ejecutando';
		private const FINISH:String = 'terminado';
		private const BLOCKED:String = 'bloqueado';
		private const PERIODO_TIMER_PPAL:uint = 1000;//ms
		private const PERIODO_TIMER_TIEMPO:uint = 100;//ms
		private const VERDE:uint = 0x00FF00;
		private const AMARILLO:uint = 0xFFFF00;
		private const ROJO:uint = 0xFF0000;

		[Bindable]
		public var view:MainView;
		
		private var _state:String;
		private var _model:MainModel = new MainModel();
		private var _timerPrincipal:Timer;
		private var _timerTiempo:Timer;
		private var tiempoComienzo:int;
		private var NARANJAS_POR_CAJA:int = 10;
		
		public function MainController()
		{			
		}
		
		public function set state(value:String):void
		{
			view.currentState = _state = value;
			var color:uint = 0;
			if(_state == INITIAL || _state == FINISH || _state == PAUSED)
				color = AMARILLO;
			else if(_state == RUNNING)
				color = VERDE;
			else if(_state == BLOCKED)
				color = ROJO;
			view.rightPanel.estado.fill = new SolidColor(color);
		}

		public function init():void
		{
			addEventListeners();	
		}
		
		private function start():void
		{
			tiempoComienzo = getTimer();
			resetTimers();
			iniciarTimers();
			this.state = RUNNING;
		}
		
		private function addEventListeners():void
		{
			_model.addEventListener(MainModel.COMPLETE, onComplete);			
			_model.addEventListener(MainModel.UPDATE, onModelUpdate);			
			_model.addEventListener(MainModel.UMBRAL_DEFECTUOSAS_AlCANZADO, onUmbralAlcanzado);
			
			view.leftPanel.btnNormal.addEventListener(MouseEvent.CLICK, onClickNormal);
			view.leftPanel.btnContinuar.addEventListener(MouseEvent.CLICK, onClickContinuar);
			view.leftPanel.btnDefectuoso.addEventListener(MouseEvent.CLICK, onClickDefectuoso);
			view.leftPanel.btnDesbloquear.addEventListener(MouseEvent.CLICK, onClickDesbloquear);
			view.leftPanel.btnBloquear.addEventListener(MouseEvent.CLICK, onClickBloquear);
			view.leftPanel.btnPausar.addEventListener(MouseEvent.CLICK, onClickPausar);
		}
		
		private function removeEventListeners():void
		{
			_model.removeEventListener(MainModel.COMPLETE, onComplete);			
			_model.removeEventListener(MainModel.UPDATE, onModelUpdate);			
			_model.removeEventListener(MainModel.UMBRAL_DEFECTUOSAS_AlCANZADO, onUmbralAlcanzado);			
		}

		private function iniciarTimers():void{
			_timerPrincipal = new Timer(PERIODO_TIMER_PPAL);
			_timerPrincipal.addEventListener(TimerEvent.TIMER, avanzarCintaTransportadora);
			_timerPrincipal.start();
			
			_timerTiempo = new Timer(PERIODO_TIMER_TIEMPO);
			_timerTiempo.addEventListener(TimerEvent.TIMER, refrescarTiempo);
			_timerTiempo.start();
		}
		
		private function resetTimers():void{
			if (_timerPrincipal){
				_timerPrincipal.removeEventListener(TimerEvent.TIMER, avanzarCintaTransportadora);
				_timerPrincipal.stop();
			}
			if (_timerTiempo){
				_timerTiempo.removeEventListener(TimerEvent.TIMER, refrescarTiempo);
				_timerTiempo.stop();
			}
		}
		
		
		private function refrescarTiempo(e:TimerEvent):void
		{
			var ahora:int = getTimer();				
			var tiempoOcurrido:int = (ahora - tiempoComienzo) * 0.001;
			view.rightPanel.tiempoTanda.text = tiempoOcurrido.toString()+"s";
		}
		
		private function avanzarCintaTransportadora(evt:TimerEvent):void 
		{
			_model.next();
		}
		
		private function crearPopUp(mensaje:String):void {
			Alert.show(mensaje,mensaje,Alert.OK,null,null);
		}
		
		/* Model listeners *************************************************************/
		protected function onComplete(event:Event):void
		{
			seleccionarTabReportes();
			_timerPrincipal.stop();
			_timerTiempo.stop();
			crearPopUp("Tanda finalizada");
			this.state = FINISH;		
			mostrarReportes();
		}
		
		protected function mostrarReportes():void
		{
			view.rightPanel.chartClases.dataProvider = _model.chartClases;
			view.rightPanel.chartLegend.dataProvider = view.rightPanel.chartClases;
			view.rightPanel.chartPesos.dataProvider = _model.chartPesos;
			var vAxis:LinearAxis = new LinearAxis();
			vAxis.title = "Peso[kg]";
			view.rightPanel.chartPesos.verticalAxis = vAxis;
			var hAxis:LinearAxis = new LinearAxis();
			hAxis.title = "Naranja";
			view.rightPanel.chartPesos.horizontalAxis = hAxis;
			
			view.rightPanel.chartDiametros.dataProvider = _model.chartDiametros;
			view.rightPanel.chartDiametros.verticalAxis 
			var vAxis2:LinearAxis = new LinearAxis();
			vAxis2.title = "Diametro[m]";
			view.rightPanel.chartDiametros.verticalAxis = vAxis2;
			var hAxis2:LinearAxis = new LinearAxis();
			hAxis2.title = "Naranja";
			view.rightPanel.chartDiametros.horizontalAxis = hAxis2;
			view.rightPanel.botonTabReportes.enabled = true;
			seleccionarTabReportes();
		}
		
		protected function onModelUpdate(event:Event):void
		{
			var total_a:int = _model.amountByClass(ClasificadorNaranjas.CLASE_A); 
			var total_b:int = _model.amountByClass(ClasificadorNaranjas.CLASE_B); 
			var total_def:int = _model.amountByClass(ClasificadorNaranjas.DEFECTUOSA); 
			view.rightPanel.cajasClaseA.text = Math.ceil((total_a / NARANJAS_POR_CAJA)).toString();
			view.rightPanel.cajasClaseB.text = Math.ceil((total_b / NARANJAS_POR_CAJA)).toString();
			view.rightPanel.cajasDescartadas.text = Math.ceil((total_def / NARANJAS_POR_CAJA)).toString();
			view.rightPanel.claseA.htmlText = total_a.toString();
			view.rightPanel.claseB.htmlText = total_b.toString();
			view.rightPanel.descartadas.htmlText = total_def.toString();
			view.rightPanel.progressBar.setProgress(((total_a + total_b + total_def) / NaranjaFactory.TAMANIO_TANDA) * 100,100);
			view.rightPanel.sensorPeso.htmlText = _model.getPesoActual().toPrecision(2).toString()+"kg"; 
			view.rightPanel.sensorDiametro.htmlText = _model.getDiametroActual().toPrecision(2).toString()+"m";
			view.rightPanel.clase.htmlText = _model.getClaseActual();
			view.rightPanel.sensorColor.fill = new SolidColor(_model.getColorActual());
		}
		
		protected function onUmbralAlcanzado(event:Event):void
		{
			_timerPrincipal.stop();
			_timerTiempo.stop();
			this.state = FINISH;
			crearPopUp("Umbral de naranjas descartadas alcanzado");			
			mostrarReportes();
		}
		
		/* View listeners *************************************************************/
		protected function onClickDefectuoso(event:MouseEvent):void
		{
			_model.reset();
			_model.unprocessed = NaranjaFactory.makeTandaDefectuosa(NaranjaFactory.TAMANIO_TANDA);
			seleccionarTabPrincipal();
			view.rightPanel.botonTabReportes.enabled = false;
			start();
		}
		protected function onClickNormal(event:MouseEvent):void
		{
			_model.reset();
			_model.unprocessed = NaranjaFactory.makeTandaNormal(NaranjaFactory.TAMANIO_TANDA);
			seleccionarTabPrincipal();
			view.rightPanel.botonTabReportes.enabled = false; 
			start();
		}
		
		protected function onClickPausar(event:MouseEvent):void
		{
			_timerPrincipal.stop();
			this.state = PAUSED;
		}

		protected function onClickContinuar(event:MouseEvent):void
		{
			_timerPrincipal.start();
			this.state = RUNNING;
		}
		
		protected function onClickBloquear(event:MouseEvent):void
		{
			_timerPrincipal.stop();
			crearPopUp("Cinta transportadora bloqueada");
			this.state = BLOCKED;
		}
		
		protected function onClickDesbloquear(event:MouseEvent):void
		{
			_timerPrincipal.start();
			this.state = RUNNING;
		}
		
		private function seleccionarTabReportes():void
		{
			view.rightPanel.viewstack.selectedIndex=1;
			view.rightPanel.viewstack.validateNow();
		}
		
		private function seleccionarTabPrincipal():void
		{
			view.rightPanel.viewstack.selectedIndex=0;
			view.rightPanel.viewstack.validateNow();
		}

	}
}